package com.edgar.plugin.utils;

import android.content.Context;
import android.hardware.display.DisplayManager;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by Edgar on 2018/2/9.
 */
public final class Utils {

    private static final String TAG = "Utils";
    public static final int BUFFER_SIZE = 4096;
    private static DisplayMetrics sDisplayMetrics;
    private Utils(){}

    public static DisplayMetrics getDisplayMetrics(Context context){
        if (sDisplayMetrics == null){
            sDisplayMetrics = new DisplayMetrics();
        }
        getDefaultDisplayMetrics(context,sDisplayMetrics);
        return sDisplayMetrics;
    }

    public static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            DisplayManager displayManager = (DisplayManager) context.getSystemService(
                    Context.DISPLAY_SERVICE);
            displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
        } else {
            WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            windowManager.getDefaultDisplay().getMetrics(metrics);
        }
    }

    public static void copyFile(File srcFile,File destFile){
        try {
            FileUtils.maybeParentMkdirs(destFile);
            copy(new FileInputStream(srcFile),new FileOutputStream(destFile),BUFFER_SIZE);
        } catch (FileNotFoundException e) {
            Log.e(TAG,"File not found:"+e.getMessage(),e);
        }
    }

    public static void copy(InputStream is,OutputStream os,int byteSize){
        BufferedInputStream bis = new BufferedInputStream(is);
        BufferedOutputStream bos = new BufferedOutputStream(os);
        byte[] buffer = new  byte[byteSize];
        int len;
        try {
            while ((len = bis.read(buffer)) != -1){
                os.write(buffer,0,len);
            }
            bos.flush();
        } catch (IOException e) {
            Log.e(TAG,"Io error:"+e.getMessage(),e);
        } finally {
            IoUtils.closeQuietly(bis);
            IoUtils.closeQuietly(bos);
            IoUtils.closeQuietly(is);
            IoUtils.closeQuietly(os);
        }
    }
}
